package com.nursing.controller.utils;

import com.nursing.model.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload")
public class Upload {
    // 从配置文件读取 UPLOAD_DIR
    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping
    public Result<String> uploadFile(@RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail(400, "文件为空！");
        }

        try {
            // 确保目录存在
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 目标文件
            File dest = new File(uploadDir + file.getOriginalFilename());
            file.transferTo(dest);
            return Result.success("文件上传成功！", "/files/" + file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(500, "文件上传失败！");
        }
    }
}
